<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input size="small" style="width:200px;" v-model.trim="filters.keyWord" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input size="small" style="width:200px;" v-model.trim="filters.keyName" placeholder="请输入关键字标识"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select size="small" clearable style="width:200px;" v-model.trim="filters.type" placeholder="请选择回复类型">
            <el-option label="公众号默认回复" value="0"></el-option>
            <el-option label="单个关键词回复" value="1"></el-option>
            <el-option label="多个关键词回复" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="float:right;">
          <el-button size="small" type="primary" v-show="riskCodeAdd" icon="plus" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item style="float:right;">
          <el-button size="small" v-show="riskCodeAdd" type="primary" icon="search" v-on:click="getLogs(true)">查询</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="keyWords" stripe border highlight-current-row :height="winHeight-188" v-loading="listLoading" @selection-change="selsChange" @cell-click="dblclick" style="width: 100%;">
      <!-- <el-table-column type="selection" width="55">
      </el-table-column> -->
      <!-- <el-table-column prop="serialNo" label="序号" width="120" sortable>
      </el-table-column> -->
      <el-table-column prop="keyName" label="关键字标识" align="center" width="150" show-overflow-tooltip >
      </el-table-column>
      <el-table-column prop="keyWord" label="关键字" align="center" width="150">
      </el-table-column>
      <el-table-column prop="type" label="回复类型" align="center" width="150" sortable :formatter="formatType">
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="30" align="center" :formatter="formatStatus" sortable>
      </el-table-column>
       <el-table-column prop="replyText" label="回复内容" align="center" show-overflow-tooltip >
      </el-table-column>
      <el-table-column label="操作" fixed='right' width="100">
        <template scope="scope">
          <el-button size="small" v-show="riskCodeUpdate" type="warning" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <!-- <el-button type="primary" size="small" v-show="buttonShows(scope.$index, scope.row)"  @click="handleRecover(scope.$index, scope.row)">恢复</el-button>
          <el-button type="danger" v-show='buttonShow(scope.$index, scope.row)' size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!-- <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button> -->

      <el-pagination style="float:right" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[10, 20, 40, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-col>

    <!--新增界面-->
    <el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
      <el-form label-width="100px" :model="addForm" :rules="addFormRules" ref="addForm">
        <el-row>
        	<el-col :xs="24" :sm="20" :md="12" :lg="12">
         	 <el-form-item label="回复类型:" prop="type">
	            <el-select v-model="addForm.type" class="otherWidth" placeholder="请选择类型">
	            	<el-option label="公众号默认回复" value="0"></el-option>
		            <el-option label="单个关键词回复" value="1"></el-option>
		            <el-option label="多个关键词回复" value="2"></el-option>
	            </el-select>
         	 </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="20" :md="12" :lg="12">
          	<el-form-item label="状态:" prop="type">
	            <el-select v-model="addForm.state" class="otherWidth" placeholder="请选择类型" >
	            	<el-option label="无效" value="0"></el-option>
		            <el-option label="有效" value="1"></el-option>
	            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="20" :md="12" :lg="12">
            <el-form-item label="关键字标识:" prop="keyName">
              <el-input v-model="addForm.keyName" auto-complete="off">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="20" :md="12" :lg="12">
            <el-form-item label="关键字:" prop="keyWord">
              <el-input v-model="addForm.keyWord" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-form-item label="回复内容:" prop="replyText">
              <el-input type ="textarea" v-model="addForm.replyText" auto-complete="off"></el-input>
            </el-form-item>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog title="修改" v-model="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="120px" :rules="editFormRules" ref="editForm">
        <el-row>
        	<el-col :xs="24" :sm="20" :md="12" :lg="12">
         	 <el-form-item label="回复类型:" prop="type">
	            <el-select v-model="editForm.type" class="otherWidth" placeholder="请选择类型">
	            	<el-option label="公众号默认回复" value="0"></el-option>
		            <el-option label="单个关键词回复" value="1"></el-option>
		            <el-option label="多个关键词回复" value="2"></el-option>
	            </el-select>
         	 </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="20" :md="12" :lg="12">
          	<el-form-item label="状态:" prop="type">
	            <el-select v-model="editForm.state" class="otherWidth" placeholder="请选择类型" >
	            	<el-option label="无效" value="0"></el-option>
		            <el-option label="有效" value="1"></el-option>
	            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="20" :md="12" :lg="12">
            <el-form-item label="关键字标识:" prop="keyName">
              <el-input v-model="editForm.keyName" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="20" :md="12" :lg="12">
            <el-form-item label="关键字:" prop="keyWord">
               <el-input v-model="editForm.keyWord" auto-complete="off"></el-input>
          </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="回复内容:" prop="replyText">
            <el-input type="textarea" v-model="editForm.replyText" auto-complete="off"></el-input>
          </el-form-item>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import util from '../../common/js/util'
import { mapState, mapActions } from 'vuex'
import commons from '../../common/js/common'
//import NProgress from 'nprogress'
import { weChatKeywords, updateKeywordWeChat, addKeywordWeChat } from '../../api/api';
export default {
  data() {
    return {
      filters: {
        keyName:'',
        keyWord:'',
        type:''
      },
      keyWords: [],
      lists: [],
      exportTotal: 0,
      loading: '',
      total: 0,
      page: 1,
      pageSize: 10,
      listLoading: false,
      sels: [],//列表选中列
      userid: '',
      addFormVisible: false,//新增界面是否显示
      editFormVisible: false,//修改界面是否显示
      editLoading: false,
      riskCodeAdd: false,
      riskCodeRemove: false,
      riskCodeUpdate: false,

      addFormRules: {
        replyText: [
          { required: true, message: '请输入回复内容', trigger: 'blur' }
        ],
        keyWord: [
          { required: true, message: '请输入关键字', trigger: 'blur' }
        ],
        keyName: [
          { required: true, message: '请输入关键字标识', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择回复类型', trigger: 'blur' }
        ]
      },
      editFormRules: {
        replyText: [
          { required: true, message: '请输入回复内容', trigger: 'blur' }
        ],
        keyWord: [
          { required: true, message: '请输入关键字', trigger: 'blur' }
        ],
        keyName: [
          { required: true, message: '请输入关键字标识', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择回复类型', trigger: 'blur' }
        ]
      },
      //修改界面数据
      editForm: {
        id: '',
        keyWord: '',
        keyName: '',
        state:'',
        type: '',
        replyText:'',
      },
      detailFormVisible: false,//新增界面是否显示
      addLoading: false,
      IsShow: false,
      detailFormRules: {
        // name: [
        //   { required: true, message: '请输入姓名', trigger: 'blur' }
        // ]
      },
      //新增界面数据
      addForm: {
        keyWord: '',
        keyName: '',
        type: '',
        state:'',
        replyText:'',
      }

    }
  },
  computed: mapState({
    clist: 'riskCodelist',
    winHeight: 'winHeight'
  }),
  methods: {
    ...mapActions([
      'CodeList'
    ]),
    formatStatus :function(row, column){
      return row.state == '1' ? '有效' : (row.state == '0' ? '无效' : '');
    },
    formatType :function(row, column){
    	if (row.type =='0') {
    		return "公众号默认回复";
    	}else if (row.type =='1') {
    		return "单个关键词回复";
    	}else{
    		return "多个关键词回复";
    	}
    },
    // buttonShow(index, row) {
    //   return row.state == '1' ? true : false;
    // },
    // buttonShows(index, row) {
    //   return row.state == '0' ? true : false;
    // },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },
    inquiry() {
      let para = new FormData();
      para.append("userId", this.addForm.userid);
      LdapUser(para).then((res) => {

        if (res.data.state == 0) {
          this.addForm.username = res.data.result.username;
          this.addForm.password = res.data.result.password;
          this.addForm.mobileno = res.data.result.mobileno;
          this.addForm.creater = res.data.result.creater;
          this.addForm.phoneno = res.data.result.phoneno;
          this.addForm.branchcode = res.data.result.branchcode;
          this.addForm.deptcode = res.data.result.deptcode;
          this.addForm.email = res.data.result.email;
          this.addForm.sex = res.data.result.sex;
          this.addForm.clevel = res.data.result.clevel;
          this.addForm.termcode = res.data.result.termcode;
          this.addForm.remarks = res.data.result.remarks;
        }
        else {
          this.$message({
            message: '未查到该用户的相关信息',
            type: 'error'
          })
        }
      });

    },
    
    handleCurrentChange(val) {
      this.page = val;
      this.getLogs(true);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getLogs(true);
    },
    //获取用户列表
    getLogs(bool) {
      let para = new FormData();
      para.append("type", this.filters.type);
      para.append("keyName", this.filters.keyName);
      para.append("keyWord", this.filters.keyWord);
      para.append("pageSize", bool ? this.pageSize : this.exportTotal);
      para.append("pageNumber", bool ? this.page : 1);
      this.listLoading = bool;
      //NProgress.start();
      if (!bool) {
        this.loading = this.$loading({
          lock: true,
          text: '正在导出',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      }

      weChatKeywords(para).then((res) => {
      	console.log(res);
        this.total = res.data.result.totalElements;
        this.exportTotal = res.data.result.totalElements;
        this.lists = res.data.result.content;
        this.listLoading = false;

        if (!bool) {
          this.loading.close();
          this.export2Excel();
        }
        else {
          this.keyWords = res.data.result.content;
        }
        //NProgress.done();
      });
    },
    //详情
    dblclick(row, column, cell, event) {

      if (column.label == '用户ID') {
        this.detailFormVisible = true;
        this.detailForm = row;
        this.detailForm.lastlogindate = commons.getDaytime(row.lastlogindate, 1);
        this.detailForm.logoutdate = commons.getDaytime(row.logoutdate, 1);
        this.detailForm.created = commons.getDaytime(row.created, 1);
        this.detailForm.disableddate = commons.getDaytime(row.disableddate, 1);
        this.detailForm.status = row.status;
        this.rowID = row.id;
      }
    },
    //恢复
    handleRecover: function (index, row) {
      this.$confirm('确认恢复该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let para = new FormData();
        para.append("userid", row.userid);
        para.append("type", "1");
        updateAdminStauts(para).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '恢复成功',
            type: 'success'
          });
          this.getLogs(true);
        });
      }).catch(() => {

      });
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let para = new FormData();
        para.append("id", row.id);
        removeRisk(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getLogs(true);
        });
      }).catch(() => {

      });
    },

    //table导出excel
    exportExcels: function () {
      this.getLogs(false);
    },
    export2Excel: function () {
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../vendor/Export2Excel');
        const tHeader = ['用户ID', '用户名', '密码', '机构', '部门', '小组', '用户级别', '性别', '电话', '手机', '邮箱', '登陆次数', '最近登陆时间', '退出时间', '登陆IP', '备注', '创建日期', '创建人', '授权类型', '注销日期', '状态', '授权级别'];
        const filterVal = ['userid', 'username', 'password', 'branchcode', 'deptcode', 'termcode', 'clevel', 'sex', 'phoneno', 'mobileno', 'email', 'loginnum', 'lastlogindate', 'logoutdate', 'loginip', 'remarks', 'created', 'creater', 'authtype', 'disableddate', 'status', 'authLevel'];
        const list = this.lists;
        for (var i in list) {
          list[i].sex = list[i].sex == "M" ? '男' : '女';
        }
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '用户列表excel');
      })
    },
    formatJson: function (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },

    //显示修改界面
    handleEdit: function (index, row) {
    	console.log(row);
      this.editForm = Object.assign({}, row);
      this.editFormVisible = true;
      // this.editForm.id = row.id;
      // this.editForm.type = row.type;
      // this.editForm.state = row.state;
      // this.editForm.keyName = row.keyName;
      // this.editForm.keyWord = row.keyWord;
      // this.editForm.replyText = row.replyText;
    },
    //显示新增界面
    handleAdd: function () {
      this.addFormVisible = true;
      this.addForm = {
        keyWord: '',
        keyName: '',
        type: '',
        state:'',
        replyText:'',
      };
    },
    //新增提交
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            //NProgress.start();
            let para = this.addForm;
            addKeywordWeChat(para).then((res) => {
              this.addLoading = false;
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['addForm'].resetFields();
              this.addFormVisible = false;
              this.getLogs(true);
            });
          });
        }
      });
    },
    //修改
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            let para = this.editForm;

            updateKeywordWeChat(para).then((res) => {
              if (res.data.success) {
                this.editLoading = false;
                //NProgress.done();
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['editForm'].resetFields();
                this.editFormVisible = false;
                this.getLogs(true);
              }
              else {
                this.editLoading = false;
                this.$message({
                  message: res.data.result,
                  type: 'error'
                });
                this.editFormVisible = false;
              }
            }).catch(() => {
              this.editLoading = false;
            });
          });
        }
      });
    },

    selsChange: function (sels) {
      this.sels = sels;
    },
   
    btnShow: function () {
      let thisData = JSON.parse(sessionStorage.getItem('155'));
      let _this = this;
      $.each(thisData, function (i, j) {
        if (thisData[i] == "riskCodeAdd") {
          _this.riskCodeAdd = true;
        }
        if (thisData[i] == "riskCodeRemove") {
          _this.riskCodeRemove = true;
        }
        if (thisData[i] == "riskCodeUpdate") {
          _this.riskCodeUpdate = true;
        }
      });
    }
  },
  mounted() {
    // this.CodeList('RiskCode');
    this.getLogs(true);
    this.btnShow();
  }
}

</script>

<style scoped>

</style>